package com.ajun.direct;

import com.ajun.common.ConnectionFactoryBuilder;
import com.ajun.common.QueueConstants;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 * direct Routing 模式 - 消费者
 *
 * @author AJun
 * @date 2021-07-14
 */
@Slf4j
public class Consumer {

    public static void main(String[] args) {
        new Thread(runnable, QueueConstants.DIRECT_QUEUE1).start();
        new Thread(runnable, QueueConstants.DIRECT_QUEUE2).start();
        new Thread(runnable, QueueConstants.DIRECT_QUEUE3).start();
    }

    private static final Runnable runnable = () -> {
        final String queueName = Thread.currentThread().getName();
        Connection connection = null;
        Channel channel = null;
        try {
            // 创建连接 Connection
            connection = ConnectionFactoryBuilder.getConnection("消费者");
            // 获取通道 Channel
            channel = connection.createChannel();
            // 接收消息
            Channel finalChannel = channel;
            finalChannel.basicConsume(queueName, true,
                (consumerTag, delivery) -> {
                    log.debug(String.valueOf(delivery.getEnvelope().getDeliveryTag()));
                    log.debug("{} 接收消息 => 消息接收成功, message => {}", queueName, new String(delivery.getBody(), StandardCharsets.UTF_8));
                },
                consumerTag -> log.error("消息接收失败"));
            System.in.read();
        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        } finally {
            ConnectionFactoryBuilder.close(channel, connection);
        }
    };
}
